package com.dearbinge.utils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 唯一号规则生成
 *
 * @author wenyi
 */
public class CodeUtil {
	
	/**
	 * 字符串转换unicode
	 */
	public static String stringToUnicode(String string) {
		StringBuffer unicode = new StringBuffer();
		for (int i = 0; i < string.length(); i++) {
			// 取出每一个字符
			char c = string.charAt(i);
			// 转换为unicode
			unicode.append("\\u" + Integer.toHexString(c));
		}
		return unicode.toString();
	}

	/**
	 * unicode 转字符串
	 */
	public static String unicodeToString(String unicode) {
		StringBuffer string = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
		for (int i = 1; i < hex.length; i++) {
			// 转换出每一个代码点
			int data = Integer.parseInt(hex[i], 16);
			// 追加成string
			string.append((char) data);
		}
		return string.toString();
	}

	/**
	 * 返序列化
	 * @param fis
	 * @return
	 */
	public static String setSerializalbe(InputStream fis) {
		ObjectInputStream ois = null;
		try {
			ois = new ObjectInputStream(fis);
			String str = (String) ois.readObject();
			return str;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				if (ois != null) {
					ois.close();
				}
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 序列化方法
	 * @param src
	 * @return
	 */
	public static byte[] getSerializalbe(String src) {
		ByteArrayOutputStream bos = null;
		ObjectOutputStream os = null;
		try {
			bos = new ByteArrayOutputStream();
			os = new ObjectOutputStream(bos);
			os.writeObject(src);
			os.flush();
			byte[] b = bos.toByteArray();
			return b;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (os != null) {
					os.close();
				}
				if (bos != null) {
					bos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 生成唯一订单号 6位日期 + 11位随机号
	 */
	public static String generateOrdersNo() {
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
		String dateNowStr = sdf.format(d);
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if (hashCodeV < 0) {
			// 有可能是负数
			hashCodeV = -hashCodeV;
		}
		return dateNowStr + String.format("%011d", hashCodeV);
	}

	/**
	 * 生成唯一商品号 6位日期 + 9位随机号
	 */
	public static String getCommodityCode() {
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
		String dateNowStr = sdf.format(d);
		int hashCodeV = UUID.randomUUID().toString().hashCode();
		if (hashCodeV < 0) {
			// 有可能是负数
			hashCodeV = -hashCodeV;
		}
		return dateNowStr + String.format("%09d", hashCodeV);
	}

	/**
	 * 获取当前时间进行格式
	 * @param format
	 * @return
	 */
	public static String setTimeFormat(String format) {
		Date now = new Date();
		SimpleDateFormat f = new SimpleDateFormat(format);
		return f.format(now);
	}

}
